<?php 
class DBManager {
	//singleton instance
	private static $instance;
	private $config_file;
	
	//private constructor
	private function __construct() {}
	
	//returns the singleton instance
	public static function getInstance($config_file) {
		if (!self::$instance) {
			self::$instance = new self();
			self::$instance->config_file = $config_file;
			return self::$instance; 
		}
	}
	
	public function test($username,$pwd) {
		$msg = null;
		$db_conn=null;
		try {
			$db_conn = mysql_connect($this->config_file['mysql_server'],$username,$pwd);
			if (!$db_conn) {
				$msg = "Invalid username and/or password.";
			} else {
				$db = mysql_select_db($this->config_file['mysql_database'],$db_conn);
				if (!$db) {
					$msg = "Invalid username and/or password.";
				}
			}
		} catch (Exception $e) {
			$msg = $e->getMessage();
		}
		return $msg;
	}
	
	public function fetchConnection() {
		$db_conn = mysql_connect($this->config_file['mysql_server'],$this->config_file['mysql_user'],$this->config_file['mysql_password'],true);
		if (!$db_conn) {
			throw new Exception("Failed to connect to database");
		} else {
			$db = mysql_select_db($this->config_file['mysql_database'],$db_conn);
			if (!$db) {
				throw new Exception("Failed to open database");
			}
		}
		return $db_conn;
	}
	
	public function beginTransaction($conn) {
		mysql_query("begin");
	}
	
	public function commit($conn) {
		endTransaction($conn,"commit");
	}
	
	public function rollback($conn) {
		endTransaction($conn,"rollback");
	}
	
	private function endTransaction($conn,$commit) {
		mysql_query($commit);
		releaseConnection($conn);
	}

	public function releaseConnection($conn) {
		mysql_close($conn);
	}
	
	//process a query
	public function processQuery($query,$conn) {
			mysql_set_charset("utf8",$conn); 
			$result = mysql_query($query,$conn);
			if (!$result) {
				throw new Exception ("Invalid execution: for '" . $query . "'");
			}
			return $result; 
	}
}
?>